package com.jastar.android.test;

import android.app.Application;
import android.content.res.Configuration;

import androidx.annotation.NonNull;
import androidx.room.Room;

import com.jastar.android.test.base.room.database.BookDatabase;

import java.util.HashMap;

/**
 * 全局应用实例
 * APP运行过程有且仅有一个实例贯穿整个生命周期
 */
public class MyApplication extends Application {

    private static MyApplication app;
    /** 存储全局变量 */
    private final HashMap<String, String> infoMap = new HashMap<>();
    private BookDatabase bookDatabase;

    public static MyApplication getInstance() {
        return app;
    }

    public String put(String key, String value) {
        return infoMap.put(key, value);
    }

    public String get(String key) {
        return infoMap.get(key);
    }

    public BookDatabase getBookDatabase() {
        return this.bookDatabase;
    }

    /** APP启动时调用 */
    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        bookDatabase = Room.databaseBuilder(this, BookDatabase.class, "book")
                //允许迁移数据库(发生DDL时，Room默认删除原库后新建，导致原记录会丢失)
                .addMigrations()
                //允许在主线程操作数据库(正式环境及默认情况不能在主线程操作数据库)
                .allowMainThreadQueries().build();
    }

    /** APP终止时调用 */
    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    /** 配置改变时调用，例如竖屏横屏切换 */
    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

}
